package com.fenda.jetpacknavigation.roomdata;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;


//exprotSchema=false 不导出数据库到本地文件
@Database(entities = {User.class},version = 1,exportSchema = false)
public abstract class UserDatabase extends RoomDatabase {
    private static volatile UserDatabase INSTANCE;

    //应保证在内存中拿到的Dao数据库操作对象是单例的

    public abstract UserDao getUserDao();

    public static UserDatabase getInstance(Context context){
        if (INSTANCE == null){
            synchronized (UserDatabase.class){
                if (INSTANCE == null){
                    INSTANCE = Room
                            .databaseBuilder(context.getApplicationContext(),UserDatabase.class,"user.db")
                            .addMigrations(MIGRATION1_2)
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    //数据库版本迁移
    static final Migration MIGRATION1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull  SupportSQLiteDatabase database) {
            //增加一个列
            database.execSQL("ALTER TABLE user ADD COLUMN flag INTEGER NOT NULL DEFAULT 0");
        }
    };

    static final Migration MIGRATION3_4 = new Migration(3,4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //增表，数据复制，删表，该表名
            database.execSQL("CREATE TABLE user_temp (id INTEGER PRIMARY KEY NOT NULL , name TEXT , " +
                    "age INTEGER " +
                    "" +")");
            database.execSQL("INSERT INTO user_temp (id,name,age) " +
                    "SELECT id,firstname FROM user" +
                    "");
            database.execSQL("DROP TABLE user");
            database.execSQL("ALTER TABLE user_temp RENAME TO user");
        }
    };
}
